package mo.leetcode_top;

import java.util.Arrays;

public class L743 {

    public int networkDelayTime(int[][] times, int n, int k) {

        int INF = Integer.MAX_VALUE / 2;

        int[][] g = new int[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(g[i], INF);
        }

        for (int[] t : times) {
            int x = t[0] - 1, y = t[1] - 1;
            g[x][y] = t[2];
        }

        int[] dist = new int[n];    //每个节点距离源点的距离
        Arrays.fill(dist, INF);
        dist[k-1] = 0;

        boolean[] used = new boolean[n];

        for (int i = 0; i < n; i++) {
            int x = -1;
            for (int j = 0; j < n; j++) {
                if (!used[j] && (x == -1 || dist[j] < dist[x])) {
                    x = j;  //每一次都找到最小的作为起点
                }
            }

            used[x] = true;
            for (int y = 0; y < n; y++) {
                dist[y] = Math.min(dist[y], dist[x] + g[x][y]);
            }

        }

        @SuppressWarnings("ConstantConditions")
        int ans = Arrays.stream(dist).max().getAsInt();
        return ans != INF ? ans : -1;
    }

}
